package com.ridaizu.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.ridaizu.common.Common;
import com.ridaizu.dao.db.DBManager;

public class GlobalFilter implements Filter {

	protected static Logger systemLogger = Logger.getLogger("system");

	private static final String LOG_FORMAT = "Servlet path: %s, PathInfo: %s, Remote ip: %s";

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;

		String requestUrl = request.getRequestURI();

		//Staticファイルをスキップする
		if(requestUrl.indexOf("/global/")>-1 || requestUrl.indexOf("/images/")>-1 || requestUrl.indexOf("/js/")>-1
				|| requestUrl.indexOf("/css/")>-1 || requestUrl.indexOf("/javax.faces.resource/")>-1 ){
			chain.doFilter(req, res);
			return;
		}

//		if (!SamlClientServlet.isPrepared(request, response)) {
//            return;
//        }

		String remoteIp = Common.getRemoteAddress(request);
		systemLogger.debug(String.format(LOG_FORMAT, request.getServletPath(), request.getPathInfo(), remoteIp));

		try{
			chain.doFilter(req, res);
		}finally{
			DBManager.closeConnection();
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
